<?php
namespace Common\Cache;

class ParameterCache {
  private $keyName = 'parameter';

  private $backendCache = null;

  public function __construct($backendCache) {
    $this -> backendCache = $backendCache;
  }

  public function getCache($id = null, $is_clear = false, $lifetime = 86400) {
    $getCache = $this -> backendCache -> get($this -> keyName, $lifetime);

    if(!$getCache || $is_clear) {
      $getCache = [];

      $findModel = \Common\Models\SysParameterModel::find();

      foreach($findModel as $value) {
        switch($value -> type) {
          case 157:
          case 162:
            $value -> value = json_decode($value -> value, true);
        }

        $getCache[$value -> key] = $value -> toArray();
      }

      $this -> backendCache -> save($this -> keyName, $getCache, $lifetime);

      if($id) {
        if(!isset($getCache[$id])) {
          return null;
        }
        return $getCache[$id];
      }
    }

    if($id) {
      if(isset($getCache[$id])) {
        return $getCache[$id];
      }
      return $this -> getCache($id, true, $lifetime);
    }

    return $getCache;
  }
}
?>